import {
	config
} from "./config.js";


let lock = false;

class HTTP {
	static KEY = 'Authorization'
	request({
		url,
		data,
		method,
		header,
		loading
	}) {
		// console.log(arguments[0]);
		const Authorization = uni.getStorageSync('Authorization')
		if (!header) {
			header = {
				sourceType: 'api'
			}
		}
		if (!method) {
			method = 'POST'
		}
		if (Authorization) {
			header['Authorization'] = Authorization
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: `${config.apiBaseUrl}` + url,
				data,
				method,
				header,
				success: (res) => {
					if (res.data.code == 1000) { // Authorization过期
						// Authorization失效 清除缓存 回到登录页
						if (!lock) {
							lock = true;
							uni.removeStorageSync('Authorization');
							uni.showModal({
								title: '提示',
								content: '登录已过期,请重新登录',
								showCancel: false,
								confirmColor: "#4dbd13",
								success(res) {
									if (res.confirm) {
										lock = false;
										try {
											uni.reLaunch({
												url: '/pages/login/login'
											});
										} catch (e) {
											// error
										}
									}
								}
							})
						}
					}
					if (res.data.code == 403) { // 请求路径错误

					}
					if (res.data.code == 500) { // 参数错误
					}
					//弹窗无广告
					if (res.data.code == 21001) {
					}
					resolve(res.data)
					loading && uni.hideLoading()
				},
				fail: (err) => {
					reject(err)
					loading && uni.hideLoading()
				}
			})
		})
	}
}

export default HTTP
